//
//  TKYProgressController.m
//  StationHouseHelper
//
//  Created by apple on 2018/5/7.
//  Copyright © 2018年 铁科院. All rights reserved.
//

#import "TKYProgressController.h"
#import "TKYProgressModel.h"
#import "TKYProgressViewCell.h"
#import "TKYSearchBarTextFiled.h"
#import "TKYUpdateProgressController.h"
#import "TKYSearchProgressResultController.h"
#import "TKYProgressDetailsController.h"
#import "TKYAddProgressController.h"
@interface TKYProgressController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property (nonatomic, strong)BaseTabelView *tableV;

@property (nonatomic, strong)TKYSearchBarTextFiled *searchBar;
/**
 当前显示的页数
 */
@property (nonatomic, assign)NSInteger currentPage;

/**
 进度日报列表数据
 */
@property (nonatomic, strong)NSMutableArray <TKYProgressModel *>*progressModelS;

@end

@implementation TKYProgressController

/**
 视图将要出现
 */
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableV.mj_header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置界面
    [self setupUI];
    [self requestrequestProgressReportListData];
}

/**
 请求进度列表数据
 */
- (void)requestrequestProgressReportListData{
    self.currentPage = 1;
    NSString *url = [NSString stringWithFormat:@"%@%@token=%@&limit=20&page=%ld",kProgressApiBaseUrl,kProgressReportListUrl,[[NSUserDefaults standardUserDefaults]objectForKey:kToken],self.currentPage];
    [SVProgressHUD showWithStatus:@"正在请求数据..."];
    [KHttpRequestTool GET:url parameters:nil success:^(id response) {
        if ([response[@"code"] integerValue] == 0) {
            self.progressModelS = [TKYProgressModel  mj_objectArrayWithKeyValuesArray:response[@"pageUtil"][@"list"]];
        }else{
            [SVProgressHUD showErrorWithStatus:@"请求失败"];
        }
        [self.tableV reloadData];
        [SVProgressHUD dismiss];
        [self.tableV.mj_header endRefreshing ];
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误, 请稍候再试"];
        [self.tableV.mj_header endRefreshing ];
    }];
}

- (void)loadMoreData{
    self.currentPage ++;
    NSString *url = [NSString stringWithFormat:@"%@%@token=%@&limit=20&page=%ld",kProgressApiBaseUrl,kProgressReportListUrl,[[NSUserDefaults standardUserDefaults]objectForKey:kToken],self.currentPage];
    [SVProgressHUD showSVProgressImage:nil Duration:1.0 FontSize:16 status:@"正在加载"];
    [KHttpRequestTool GET:url parameters:nil success:^(id response) {
        NSArray *arr = [TKYProgressModel  mj_objectArrayWithKeyValuesArray:response[@"pageUtil"][@"list"]];
        [self.progressModelS addObjectsFromArray:arr];
        [self.tableV reloadData];
        int total = [response[@"pageUtil"][@"totalCount"] intValue];
        if (self.currentPage == total) { // 全部加载完毕
            // 提示用户:没有更多数据
            [self.tableV.mj_footer endRefreshingWithNoMoreData];
            //            self.tableV.mj_footer.hidden = YES;
        } else { // 还没有加载完全
            // 结束刷新
            [self.tableV.mj_footer endRefreshing];
        }
        //NSLog(@"%@",response[@"rows"]);
    } failure:^(NSError *error) {
        [SVProgressHUD showSVProgressImage:nil Duration:1.0 FontSize:16 status:@"网络错误,请稍候再试"];
        [self.tableV.mj_footer endRefreshing];
    }];
}

- (void)loadNewData{
    [self requestrequestProgressReportListData];
}

- (void)deleteProgressModel:(TKYProgressModel *)progressModel{
    NSString *url = [NSString stringWithFormat:@"%@%@",kProgressApiBaseUrl,kDeleteProgressReportUrl];
    NSDictionary *parameterDict = @{
                                    @"token":[[NSUserDefaults standardUserDefaults]objectForKey:kToken],
                                    @"id":progressModel.ID
                                    };
    [KHttpRequestTool POST:url parameters:parameterDict success:^(id response) {
        if ([response[@"code"] integerValue] == 0) {
            [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"删除成功"];            //[SVProgressHUD dismiss];
            [self.tableV reloadData];
        }else{
            [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:response[@"msg"]];
        }
        [self.tableV.mj_header endRefreshing ];
    } failure:^(NSError *error) {
        [SVProgressHUD showSVProgressImage:nil Duration:1.0 FontSize:16 status:@"网络错误,请稍候再试"];
    }];
}
/**
 界面设置
 */
- (void)setupUI{
    self.navigationItem.title = @"进度显示";
    self.navigationController.navigationBar.barTintColor = KNavColor;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:19.0]}];
    [self.view addSubview:self.tableV];
    [self.tableV setTableHeaderView:self.searchBar];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"新增" style:UIBarButtonItemStylePlain target:self action:@selector(addProgressAction:)];
}

#pragma mark--填报进度
- (void)addProgressAction:(UIBarButtonItem *)barButtonItem{
    TKYAddProgressController  *addProgressVC = [[TKYAddProgressController alloc]init];
    [self.navigationController pushViewController:addProgressVC animated:YES];
}

#pragma mark-- UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.progressModelS.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 95;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TKYProgressViewCell *cell = [tableView dequeueReusableCellWithIdentifier:KProgressViewCellID];
    cell.progressModel = self.progressModelS[indexPath.row];
    return cell;
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    TKYProgressModel *model = self.progressModelS[indexPath.row];
    //删除
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除"handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        [self deleteProgressModel:model];
        [self.progressModelS removeObject:model];
        [self.tableV reloadData];
        [tableView setEditing:NO animated:YES];  // 这句很重要，退出编辑模式，隐藏左滑菜单
    }];
    
    //修改
    UITableViewRowAction *updataAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"修改"handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"修改");
        TKYUpdateProgressController *updateVC = [[TKYUpdateProgressController alloc]init];
        updateVC.progressModel = model;
        [self.navigationController pushViewController:updateVC animated:YES];
    }];
    deleteAction.backgroundColor = [UIColor grayColor];
    return @[deleteAction, updataAction];
}

//- (nullable UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(tvos){
//    
//    // delete action
//    TKYProgressModel *model = self.progressModelS[indexPath.row];
//
//    UIContextualAction *deleteAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"删除" handler:^(UIContextualAction * _Nonnull action,__kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)){
//        NSLog(@"删除");
//        [tableView setEditing:NO animated:YES];  // 这句很重要，退出编辑模式，隐藏左滑菜单
//        [self deleteProgressModel:model];
//        [self.progressModelS removeObjectAtIndex:indexPath.row];
//        [self.tableV deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationMiddle];
//        [self.tableV reloadData];
//        completionHandler(true);
//        
//    }];
//    UIContextualAction *upAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"修改" handler:^(UIContextualAction * _Nonnull action,__kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)){
//        NSLog(@"修改");
//
//        TKYUpdateProgressController *updateVC = [[TKYUpdateProgressController alloc]init];
//        updateVC.progressModel = model;
//        [self.navigationController pushViewController:updateVC animated:YES];
//        completionHandler(true);
//        
//    }];
//    upAction.backgroundColor = [UIColor grayColor];
//
//    UISwipeActionsConfiguration *actions = [UISwipeActionsConfiguration configurationWithActions:@[upAction,deleteAction]];
//    actions.performsFirstActionWithFullSwipe = NO;
//    
//    return actions;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    TKYProgressModel *model = self.progressModelS[indexPath.row];
    TKYProgressDetailsController *progressDetailVC = [[TKYProgressDetailsController alloc]init];
    progressDetailVC.progressModel = model;
    [self.navigationController pushViewController:progressDetailVC animated:YES];
}

#pragma mark-- 懒加载
- (BaseTabelView *)tableV{
    if (_tableV == nil) {
        _tableV = [[BaseTabelView alloc]initWithFrame:CGRectMake(0, MyNavBarHeight, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
        _tableV.delegate = self;
        _tableV.dataSource = self;
        [_tableV registerNib:[UINib nibWithNibName:@"TKYProgressViewCell" bundle:nil] forCellReuseIdentifier:KProgressViewCellID];
        self.tableV.mj_footer = [TKYRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        self.tableV.mj_header = [TKYRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    }
    return _tableV;
}

- (NSMutableArray<TKYProgressModel *> *)progressModelS{
    if (_progressModelS == nil) {
        _progressModelS = [NSMutableArray array];
    }
    return _progressModelS;
}

- (TKYSearchBarTextFiled *)searchBar {
    if (!_searchBar) {
        _searchBar = [[TKYSearchBarTextFiled alloc] initWithFrame:CGRectMake(0.f, 0, self.view.kx_width, 44.f)];
        __weak typeof(self) weakSelf = self;
        _searchBar.seachbarBlock = ^(UIButton *button) {
            
            TKYSearchProgressResultController *progressResultVC = [[TKYSearchProgressResultController alloc]init];
            [weakSelf.navigationController pushViewController:progressResultVC animated:YES];
        };
    }
    return _searchBar;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
